<?php
namespace app\blog\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
class Pic extends Admin
{
    public function index(){
        $order=$this->getOrder();
        $where=$this->getMap();
        $data=db('blog_pic')->where($where)->order($order)->select();
        $atitle=[];
        for ($i=0;$i<count($data);$i++){
            $aid=$data[$i]['aid'];
            $atitle[]=db('blog_article')->where('id='.$aid)->value('title');
            $data[$i]['aid']=$atitle[$i];
        }
        return ZBuilder::make('table')
        ->addColumns([
            ['id','ID'],
            ['aid','所属文章标题'],
            ['desc','图片描述'],
            ['addtime','添加时间','datetime'],
            ['right_button','操作','btn']
        ])
        ->addOrder('id,desc')
        ->addFilter('desc')
        ->setRowList($data)
        ->addTopButtons('add,delete')
        ->addRightButtons('edit,delete')
        ->fetch();
    }
    public function edit($id=null){
        if ($this->request->isPost()){
            $update=$this->request->post();
            $update['path']=get_file_path($update['path']);
            $rs=db('blog_pic')->update($update);
            if ($rs){
                $this->success('修改成功','index');
            }else{
                $this->error('修改失败');
            }
        }
        $data=db('blog_pic')->where('id='.$id)->find();
        $articles=db('blog_article')->order('id desc')->select();
        foreach ($articles as $k=>$v){
            $k=$v['id'];
            $a[$k]=$v['title'];
        }
        return ZBuilder::make('form')
        ->addSelect('aid','选择文章','请选择文章',$a,$data['aid'])
        ->addFormItems([
            ['hidden','id'],
            ['image','path','图片'],
            ['ckeditor','desc','图片描述']
        ])
        ->fetch('',$data);
    }
    public function add(){
        if ($this->request->isPost()){
            $data=$this->request->post();
            $data['path']=get_file_path($data['path']);
            $data['addtime']=time();
            $rs=db('blog_pic')->insert($data);
            if ($rs){
                $this->success('添加成功','index');
            }else{
                $this->error('添加失败');
            }
        }
        //获得文章标题
        $atitles=db('blog_article')->order('id desc')->select();
        $w=[];
        foreach ($atitles as $k=>$v){
            $k=$v['id'];
            $w[$k]=$v['title'];
        }
        return ZBuilder::make('form')
        ->addSelect('aid','选择文章','请选择文章',$w)
        ->addFormItems([
            ['hidden','id'],
            ['image','path','图片'],
            ['ckeditor','desc','图片描述']
        ])
        ->fetch();
    }
}

?>